package 极客算法训练营.chapter09;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class 二叉树的层序遍历 {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> ans = new ArrayList<>();
            Deque<TreeNode> queue = new ArrayDeque<>();
            if (root != null) {
                queue.add(root);
            }
            while (!queue.isEmpty()) {
                //存储每一层的结果
                List<Integer> tmp = new ArrayList<>();
                int size = queue.size();//当前层的结点个数
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.pollFirst();//从左至右取
                    tmp.add(node.val);
                    //将结点的左右结点加入队列
                    if (node.left != null) {
                        queue.addLast(node.left);
                    }
                    if (node.right != null) {
                        queue.addLast(node.right);
                    }
                }
                ans.add(tmp);
            }
            return ans;
        }
    }
}
